package com.gettec.lims.client.grid;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.event.ToolBarEvent;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ButtonBar;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.Radio;
import com.extjs.gxt.ui.client.widget.form.RadioGroup;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FlowData;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.menu.Menu;
import com.extjs.gxt.ui.client.widget.menu.MenuBar;
import com.extjs.gxt.ui.client.widget.menu.MenuBarItem;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.gettec.lims.client.NlimsConstants;
import com.gettec.lims.client.bind.DateFieldBinding;
import com.gettec.lims.client.bind.RadioGroupBinding;
import com.gettec.lims.client.forms.RegSheetForm;
import com.gettec.lims.client.menu.MenuItemEx;
import com.gettec.lims.client.resources.Resources;
import com.gettec.lims.client.services.NnimsServiceAsync;
import com.gettec.lims.shared.model.RegSheet;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
public class RegSheetGridView extends Window {
	private FormBinding formBindingsh;   
	private NnimsServiceAsync service ;
	private Grid<BeanModel> grid ;
	 ListStore<BeanModel> store;
	 ContentPanel cpanel = new ContentPanel();   
	public RegSheetGridView() {
		setWidth(950);
		setResizable(false);
		 // List<MenuItemEx> list=new ArrayList<MenuItemEx>();
	        
	        Menu menu = new Menu();   
	        
	        MenuItemEx item1 = new MenuItemEx("委托登记单","新增工作单");   
	        item1.addSelectionListener(new SelectionListener<MenuEvent>()
	       		 {

	   				@Override
	   				public void componentSelected(MenuEvent ce) {
	   					// TODO Auto-generated method stub
	   					RegSheet rs=new RegSheet();
	   					RegSheetForm rf=	new RegSheetForm(service,store, rs);
	   					rf.show();
	   				}
	       	 
	       		 });
	        menu.add(item1);   
	       
	        MenuItemEx item2 = new MenuItemEx("委托登记单","修改记录数据"); 
	        /*item2.addSelectionListener(new SelectionListener<MenuEvent>()
		       		 {

		   				@Override
		   				public void componentSelected(MenuEvent ce) {
		   					// TODO Auto-generated method stub
		   					RegSheet rs=new RegSheet();
		   					RegSheetForm rf=	new RegSheetForm(service,store, rs);
		   					rf.show();
		   					if (grid.getSelectionModel().getSelectedItems() == null
		   							|| grid.getSelectionModel().getSelectedItems().size() <= 0) {
		   						MessageBox.alert("提示信息", "请选择一条记录！", null);
		   					} else {
		   						RegSheet rs = grid.getSelectionModel().getSelectedItem().getBean();
		   						service.getCustomer(customer.getId(), new AsyncCallback<Customer>() {
		   							public void onFailure(Throwable caught) {
		   								MessageBox.alert("提示信息", "操作失败！", null);
		   							}

		   							public void onSuccess(Customer result) {
		   								new CustomerDialog(customerService, store,result == null ? new Customer() : result);
		   							}
		   						});
		   					}
		   				}
		       	 
		       		 });*/
	        menu.add(item2); 
	        
	        MenuItemEx item3 = new MenuItemEx("委托登记单","删除记录数据");   
	        menu.add(item3); 
	       
	        MenuBar bar = new MenuBar();   
	        bar.setBorders(true);   
	        bar.setStyleAttribute("borderTop", "none");   
	        bar.add(new MenuBarItem("文件", menu));   
	      
	        Menu sub2 = new Menu(); 
	        MenuItemEx item4=new MenuItemEx("委托登记单","检测配置任务");
	        sub2.add(item4);   
	     
	      
	        MenuBarItem edit = new MenuBarItem("检测", sub2);   
	        bar.add(edit);   

	        cpanel.setHeading("样品信息管理");   
	        cpanel.setTopComponent(bar);   
	        
	     // menuListener(list);
	       add(cpanel, new FlowData(10));   
	}
	@Override
	protected void onRender(Element parent, int index) {
		// TODO Auto-generated method stub
		super.onRender(parent, index);
	    //---get data from server　start
		 service = (NnimsServiceAsync) Registry.get(NlimsConstants.SERVICE);
	    RpcProxy<PagingLoadResult<RegSheet>> proxy = new RpcProxy<PagingLoadResult<RegSheet>>() {   
	      @Override  
	      public void load(Object loadConfig,   
	          AsyncCallback<PagingLoadResult<RegSheet>> callback) {   
	        service.getRegSheets((PagingLoadConfig) loadConfig, callback);   
	      }   
	    };   
	 final  BasePagingLoader<PagingLoadResult<ModelData>> loader = new BasePagingLoader<PagingLoadResult<ModelData>>(   
	        proxy, new BeanModelReader());   
	    loader.setRemoteSort(true);   
	    store = new ListStore<BeanModel>(loader);   
	    //---get data from server　end
		final PagingToolBar toolBar = new PagingToolBar(50);   
	    toolBar.bind(loader);   
	  
	  
  FormPanel fpanel = new FormPanel();
	    
	   
	    final Grid<BeanModel> grid = createGrid(store);  
	    grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {   
		      public void handleEvent(GridEvent<BeanModel> be) {   
		        loader.load(0, 12);   
		      }   
		    }); 
	    createForm(grid,store,fpanel);
	   
	   
	    cpanel.setFrame(true);   
	    cpanel.setCollapsible(true);   
	    cpanel.setAnimCollapse(false);   
	    cpanel.setButtonAlign(HorizontalAlignment.CENTER);   
	    cpanel.setIcon(Resources.ICONS.table());     
	    cpanel.setHeaderVisible(false); 
	    cpanel.setSize(900, 350);   
	    cpanel.setBottomComponent(toolBar);    
	    cpanel.setLayout(new RowLayout(Orientation.HORIZONTAL));   

	    cpanel.add(grid, new RowData(.6, 1));   
	    cpanel.add(fpanel, new RowData(.4, 1));   
	   // add(panel);   

	   layout();
	  
	    	  
	  
	  }   
	private FormPanel createForm(final Grid<BeanModel> grid,final ListStore<BeanModel> store,final FormPanel fpanel ) {     
	    fpanel.setHeaderVisible(false);   
	    fpanel.setScrollMode(getScrollMode().AUTOY);
	    NumberField  client_number = new NumberField ();    
	 
	     final TextField<String> data_scope = new TextField<String>();  
		 final TextField<String> entrust_org = new TextField<String>();
		 final DateField reg_date = new DateField();   
		 final DateField limit_date = new DateField();   
		 final TextField<String> under_dept = new TextField<String>();
		 final TextField<String> bussiness_type = new TextField<String>();  
		 final TextField<String> area_info = new TextField<String>();  
		 final TextField<String> detect_type = new TextField<String>();
		 final TextField<String> detect_way = new TextField<String>();  
		 final TextField<String> report_send_way = new TextField<String>();   
		// final BooleanField issubproject = new BooleanField("issubproject");  
		// final BooleanField isconclusion_req = new BooleanField("isconclusion_req"); 
		// final BooleanField issubcontract = new BooleanField("issubcontract"); 
		 final RadioGroup issubproject = new RadioGroup("issubproject");  
		 final RadioGroup isconclusion_req = new RadioGroup("isconclusion_req"); 
		 final RadioGroup issubcontract = new RadioGroup("issubcontract"); 
		 final TextField<String> pay_type = new TextField<String>();  
		 final TextField<String> client_req = new TextField<String>();
		 final TextField<String> service_declear = new TextField<String>();  
		 final TextField<String> accepter = new TextField<String>();  
		 final TextField<String> client = new TextField<String>();
		 Field[] list={
				 client_number,data_scope,entrust_org,reg_date,limit_date,under_dept,
							bussiness_type,area_info,detect_type,detect_way,report_send_way,
							issubproject,
							isconclusion_req,issubcontract,
							pay_type,client_req,service_declear,accepter,client};
	String[] captions={"client_number","data_scope","client_org","reg_date","limit_date","under_dept","business_type","area_info","detect_type",
				"detect_way","report_send_way","issubproject","isconclusion_req","issubcontract",
				"pay_type","client_req","service_declear","accepter,","client"};
					String[] zh_captions={"委托登记号",
							"数据涵盖范围","委托单位","委托登记日期","规定完成日期","所属部门","业务类别","地区信息","检测类别",
							"委托检测方法","报告发送方式",
							"分包项目",
							"结论要求","报告是否明示分包",
							"付款方式","委托要求","服务方申明",
							"受理人,","委托人"};
				
//---------------------------------------------------------------
				    Radio issubproject_radio1 = new Radio();   
				    issubproject_radio1.setBoxLabel("是");  
				    issubproject_radio1.setValueAttribute("true");
				    Radio issubproject_radio2 = new Radio();   
				    issubproject_radio2.setBoxLabel("否");   
				    issubproject_radio2.setValueAttribute("false");
				    issubproject.add(issubproject_radio1);   
				    issubproject.add(issubproject_radio2); 
				    Radio isconclusion_req_radio1 = new Radio();   
				    isconclusion_req_radio1.setBoxLabel("是");  
				    isconclusion_req_radio1.setValueAttribute("true");
				    Radio isconclusion_req_radio2 = new Radio();   
				    isconclusion_req_radio2.setBoxLabel("否"); 
				    isconclusion_req_radio2.setValueAttribute("false");
				    isconclusion_req.add(isconclusion_req_radio1);   
				    isconclusion_req.add(isconclusion_req_radio2);  
				    
				    Radio issubcontract_radio1 = new Radio();   
				    issubcontract_radio1.setBoxLabel("是1"); 
				    issubcontract_radio1.setValueAttribute("true");
				    Radio issubcontract_radio2 = new Radio();   
				    issubcontract_radio2.setBoxLabel("否1"); 
				    issubcontract_radio2.setValueAttribute("false");
				    issubcontract.add(issubcontract_radio1);   
				    issubcontract.add(issubcontract_radio2);  
				    FormData formData = new FormData("100%");     
				    fpanel.setFrame(true);   
					for( int i=0;i<captions.length;i++)
					{
						list[i].setName(captions[i]);
						list[i].setFieldLabel(zh_captions[i]);
						
						fpanel.add(list[i], formData);   
					}
					 final FormBinding formBindings = new FormBinding(fpanel,true);//绑定必须在panel加入控件之后
					   formBindings.setStore(store);  
						formBindings.addFieldBinding(new RadioGroupBinding(issubproject));
						formBindings.addFieldBinding(new RadioGroupBinding(isconclusion_req));
						formBindings.addFieldBinding(new RadioGroupBinding(issubcontract));
						formBindings.addFieldBinding(new DateFieldBinding(reg_date));
						formBindings.addFieldBinding(new DateFieldBinding(limit_date));
						//final ModelData md;
						//final BeanModel regSheetModel;
						final Set<BeanModel> regset=new HashSet<BeanModel>();
					 grid.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);   
					    grid.getSelectionModel().addListener(Events.SelectionChange,   
					        new Listener<SelectionChangedEvent<BeanModel>>() {   
					          public void handleEvent(SelectionChangedEvent<BeanModel> be)
					          {   
					            if (be.getSelection().size() > 0) {
					            	//md=(ModelData) be.getSelection().get(0);
					            	RegSheet rg=grid.getSelectionModel().getSelectedItem().getBean();
					            	BeanModel regSheetModel= BeanModelLookup.get().getFactory(RegSheet.class).createModel(rg);
					            	
					              //formBindings.bind(md);  
					              formBindings.bind(regSheetModel);  
					              regset.add(regSheetModel);
					            } else {   
					              formBindings.unbind();   
					            }   
					          }   
					        });   
					   final ButtonBar  buttonBar=new ButtonBar();
					    Button update=new Button("修改");
					    buttonBar.add(update);
					   
					    update.addSelectionListener(new SelectionListener<ButtonEvent>() {
					    	 
							public void componentSelected(ButtonEvent ce) {
								if (fpanel.isValid()) {
									buttonBar.disable();
									// RegSheet regSheet=grid.getSelectionModel().getSelectedItem().getBean();
									 final BeanModel regSheetModel=regset.iterator().next();
									 RegSheet regSheet=regSheetModel.getBean();
									service.updateRegSheet(regSheet, new AsyncCallback<Integer>() {
										public void onFailure(Throwable caught) {							
											
											buttonBar.enable();	
											MessageBox.alert("提示信息", "保存失败！", null);
										}

										public void onSuccess(Integer result) {							
											
											buttonBar.enable();								
											
											store.add(regSheetModel);
											store.getLoader().load();
											
											MessageBox.alert("提示信息", "修改成功！", null);
										}

													
									});
								}
							}
					    });
					    Button reset = new Button("重置");
					    buttonBar.add(reset);
						reset.addSelectionListener(new SelectionListener<ButtonEvent>() {
							public void componentSelected(ButtonEvent ce) {
							
								fpanel.reset();
							}

						});
						

						Button toggle = new Button("删除"); 
						
						toggle.addSelectionListener(new SelectionListener<ButtonEvent>() { 
							 
						@Override 
						public void componentSelected(ButtonEvent ce) { 
							final BeanModel regSheetModel=regset.iterator().next();
							 RegSheet regSheet=regSheetModel.getBean();
						if (regSheet == null) { 
						MessageBox.alert("提示信息", "请选择一条记录！", null); 
						} else { 
						service.deleteRegSheet(regSheet, new AsyncCallback<Integer>() { 
						public void onFailure(Throwable caught) { 
						MessageBox.alert("提示信息", "删除失败！", null); 
						} 

						public void onSuccess(Integer result) { 
						
						store.remove(regSheetModel); 
						MessageBox.alert("提示信息", "删除成功！", null); 
						} 
						}); 
						} 
						} 
						}); 
						buttonBar.add(toggle); 


						fpanel.add(buttonBar);
						//cpanel.add(buttonBar);
	    return fpanel;   
	  }   
	  
	  private Grid<BeanModel> createGrid(ListStore<BeanModel> store) {   
 
	    store.setMonitorChanges(true);   
	    List<ColumnConfig> columns = new ArrayList<ColumnConfig>();   
	    columns.add(new ColumnConfig("client_number", "委托登记号", 100));   
	    columns.add(new ColumnConfig("client_org", "委托单位", 75));   
	    columns.add(new ColumnConfig("bussiness_type", "业务类别", 75));   
	    columns.add(new ColumnConfig("reg_date", "委托登记日期", 90));   
	    columns.add(new ColumnConfig("limit_date", "规定完成日期", 90));   
	    ColumnModel cm = new ColumnModel(columns); 
	  
	  
	    Grid<BeanModel> grid = new Grid<BeanModel>(store, cm);   
	    grid.getView().setEmptyText("  ");   
	    grid.setLayoutData(new FitLayout());

	    grid.setLoadMask(true);   
	    grid.setBorders(true);   
	    grid.setAutoExpandColumn("client_number");
		   
		 
   
	    return grid;   
	  }   

}
